import store from '../store'

//生成len个随机字符
export const randomString = function(len) {
  let $chars ='ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678' 
  let maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

export const timeFormat = function(date) {
  let year = date.getFullYear() 
  let month = (date.getMonth() + 1) >= 10 ? (date.getMonth() + 1) : '0'+(date.getMonth() + 1)
  let day = date.getDate() >= 10 ? date.getDate(): '0' + date.getDate()
  let hour = date.getHours() >=10 ? date.getHours() : '0' + date.getHours() 
  let minute = date.getMinutes() >= 10 ? date.getMinutes() : '0' + date.getMinutes() 
  let second = date.getSeconds() >= 10 ? date.getSeconds(): '0' + date.getSeconds()
  let str = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
  return str
}


export const getUrlItem = function (name, url) {
  url = url || window.location.search;
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var r = url.substr(1).match(reg);
  if (r != null) return (r[2]);
  return null;
}


export const setHeight = function (){
  let app = document.documentElement.clientHeight
  // let app = window.getBoundingClientRect().height
  let footerH = document.getElementsByClassName('footer')[0].getBoundingClientRect().height
  let height = app  - footerH
  let isRegister = store.state.app.isRegister
  if(!isRegister){
    height -= 64
  } else{
    height -= 2
  }
  height +=  'px'
  // console.log(footerH, app, height, store)
  return height
}


export const getScrollTop = function () {
  var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0
  if(document.body){
    bodyScrollTop = document.body.scrollTop
  }
  if(document.documentElement){
    documentScrollTop = document.documentElement.scrollTop
  }
  scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop
  return scrollTop
}
   
  //文档的总高度
export const getScrollHeight = function (){
  var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0
  if(document.body){
    bodyScrollHeight = document.body.scrollHeight
  }
  if(document.documentElement){
    documentScrollHeight = document.documentElement.scrollHeight
  }
  scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight
  return scrollHeight
}
  
  //浏览器视口的高度
   
export const getWindowHeight =  function () {
  var windowHeight = 0;
  if(document.compatMode == "CSS1Compat"){
    windowHeight = document.documentElement.clientHeight
  }else{
    windowHeight = document.body.clientHeight
  }
  return windowHeight
}
  
export const setSearchParams = function(params,page_size,page,order,sort){
  let searchParams = {
    filter:{},
    op:{},
  }
  for(let item in params){
    let value = params[item].value
    if(value){
      searchParams.filter[item] = value
      if(params[item].op){
        searchParams.op[item]= params[item].op
      } else {
        searchParams.op[item]= '='
      }
    }
    
  }
  if(page_size){
    searchParams.page_size = page_size
  }

  if(page){
    searchParams.page = page
  }

  if(order){
    searchParams.order = order
  }

  if(sort){
    searchParams.sort = sort
  }
  return searchParams
}


export const parseMoney = function(number, decimals, dec_point, thousands_sep) {
  /*
  * 参数说明：
  * number：要格式化的数字
  * decimals：保留几位小数
  * dec_point：小数点符号
  * thousands_sep：千分位符号
  * */
  number = (number + '').replace(/[^0-9+-Ee.]/g, '');
  var n = !isFinite(+number) ? 0 : +number,
      prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
      sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
      dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
      s = '',
      toFixedFix = function (n, prec) {
          var k = Math.pow(10, prec);
          return '' + Math.ceil(n * k) / k;
      };

  s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
  var re = /(-?\d+)(\d{3})/;
  while (re.test(s[0])) {
      s[0] = s[0].replace(re, "$1" + sep + "$2");
  }

  if ((s[1] || '').length < prec) {
      s[1] = s[1] || '';
      s[1] += new Array(prec - s[1].length + 1).join('0');
  }
  return s.join(dec);
}

export const getRouterChild = function(path, menuList) {
  let res = []
  for (let i = 0; i < menuList.length; i++) {
    const element = menuList[i];
    if(path == element.path && element.children) {
      res = element.children
    } else if(element.children && element.children.length>0){
      for (let j = 0; j < element.children.length; j++) {
        const ele = element.children[j];
        if(path == ele.path && ele.children) {
          res = ele.children
        }
      }
    }
    
  }


    

  return res
}

// 数组移除元素
Array.prototype.remove = function(val) { 
  var index = this.indexOf(val); 
  if (index > -1) { 
  this.splice(index, 1); 
  } 
  };


export const formatFileSize = function(size) {
  let value = Number(size);
  if (size && !isNaN(value)) {
      const units = [ 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', 'BB'];
      let index = 0;
      let k = value;
      if (value >= 1024) {
          while (k > 1024) {
              k = k / 1024;
              index++;
          }
      }
      return `${(k).toFixed(2)}${units[index]}`;
  }
  return '-';
}
export const getNameByMenu = function(list,path){ //获取后台维护的多语言名名称
  let name = ''
  if(list){
    for(let i =0 ;i < list.length; i++) {
      if(list[i].path == path){
        name = list[i].name
      }
    }
  }
  
  return name
}

var  utils  = {
  setCdnUrl: function(){
    let hostname = window.location.hostname
    let url = 'bonoch-test'
    if(hostname == 'bonoch.com') {
      url = 'bonoch-line'
    }
    return 'https://'+url+'.oss-us-west-1.aliyuncs.com'
  
  
  },
}
export default utils;

export const getBrowserVersions = () => {
  let u = navigator.userAgent
  // let app = navigator.appVersion
  return {
    mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
    android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1, //android终端
    iPhone: u.indexOf('iPhone') > -1, //是否为iPhone或者QQHD浏览器
    iPad: u.indexOf('iPad') > -1, //是否iPad
    webApp: u.indexOf('Safari') == -1, //是否web应该程序，没有头部与底部
    pc: !u.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  }
}

export const isMobile = () => {
  let versions = getBrowserVersions()
  return versions.mobile
}

export const isPc = () => {
  let versions = getBrowserVersions()
  return versions.pc
}
